package org.maverickjs.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.maverickjs.model.bean.UserJB;
import org.maverickjs.persistence.UserDAOImpl;
import org.maverickjs.persistence.dao.UserDAO;


@WebServlet("/login.do")
public class LoginServlet extends ServletBase {

	private static final long serialVersionUID = 1L;
    
	
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			
			UserJB user = ((UserDAO) createDAO(request, UserDAOImpl.class)).login(request.getParameter("userName"), request.getParameter("password"));
			
			if (user != null)
				request.getSession().setAttribute("user", user);
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("sucess", user != null);			
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(jsonObject);
			out.flush();
			out.close();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
